<template>
  <div class="search-container">
    <form action="/" class="search-form">
      <!-- @focus="isResultShow = false" 如果聚焦就重新显示联想组件 -->
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
    </form>
    <!-- 搜索结果 -->
    <search-result :search-text="searchText" v-if="isResultShow" />
    <!-- 搜索联想 -->
    <search-suggestion
      @search="onSearch"
      v-else-if="searchText"
      :search-text="searchText"
    />
    <!-- 历史记录 -->
    <search-history
      v-else
      :search-histories="searchHistories"
      @clear-search-histories="searchHistories = []"
      @search = "onSearch"
    />
  </div>
</template>

<script>
import { setItem, getItem } from '../../utils/storage'
import searchHistory from '../search/commponents/search-history'
import searchSuggestion from '../search/commponents/search-suggestion'
import searchResult from '../search/commponents/search-result'
export default {
  name: 'SearchIndex',
  data () {
    return {
      searchText: '',
      isResultShow: false,
      // 如果为空就是一个空数组
      searchHistories: getItem('TOUTIAO_SEARCH') || []
    }
  },
  watch: {
    // 历史记录数据永久化处理
    searchHistories (val) {
      setItem('TOUTIAO_SEARCH', val)
    }
  },
  created () {},
  mounted () {},
  methods: {
    //   按下搜索键进入搜索组件
    onSearch (val) {
      this.searchText = val
      // 检查数据是否在searchHistories历史记录中存在
      const index = this.searchHistories.indexOf(val)
      // 如果存在就删除掉
      if (index !== -1) {
        this.searchHistories.splice(index, 1)
      }
      // 然后在添加进来，保证搜索过的都在首位
      this.searchHistories.unshift(val)
      // 渲染搜索结果
      this.isResultShow = true
    },
    onCancel () {
      this.$router.back()
    }
  },
  components: {
    searchHistory,
    searchSuggestion,
    searchResult
  }
}
</script>

<style scoped lang="less">
.search-container {
  padding-top: 108px;
  .van-search__action {
    color: #fff;
  }
  .search-form {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
}
</style>
